import axios from 'axios';
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;

class DatasetAPI {
    constructor() {}

    async getDatasets() {
        try {
            const response = await axios.get(`${BASE_URL}/labeldata/count_by_dataset`);
            return response.data;
        } catch (error) {
            console.error('Error DatasetAPI::getDatasets:', error.message);
            return [];
        }
    }

    // data格式：
    // {
    //   "name": "books",
    //   "type": "OCR"
    // }
    async createDataset(name, type) {
        try {
            const response = await axios.post(`${BASE_URL}/datasets`, {
                name: name,
                type: type
            });
            return response.data;
        } catch (error) {
            console.error('Error DatasetAPI::createDataset', error.message);
            return {};
        }
    }
}

class LabeldataAPI {
    constructor() {}

    // 获取labeldata数据，参数包括dataset_id，page，perpage信息
    async getLabelData(dataset_id, page, per_page) {
        try {
            const response = await axios.get(`${BASE_URL}/labeldata?dataset_id=${dataset_id}&page=${page}&per_page=${per_page}`);
            // console.log('LabeldataAPI::getLabelData resp = ', response.data);
            return response.data;
        } catch (error) {
            console.error('Error LabeldataAPI::getLabelData:', error.message);
            return { current_page: 1, labeldata: [], total_pages: 1, total_records: 0 };
        }
    }

    async createLabelData(data) {
        try {
            const response = await axios.post(`${BASE_URL}/labeldata`, data);
            return response.data;
        } catch (error) {
            console.error('Error LabeldataAPI::createLabelData:', error.message);
            return {};
        }
    }

    async saveLabelData(label_data_id, label_result) {
        // console.log('saveLabelData label_result = ', label_result);
        try {
            let headers = {
                'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryn8D9asOnAnEU4Js0'
            };
            let formData = new FormData();
            formData.append('label_type', 'manuallabel');
            formData.append('label_result', label_result);
            const response = await axios.post(`${BASE_URL}/labeldata/${label_data_id}`, formData, { headers: headers });
            return response.data;
        } catch (error) {
            console.error('Error LabeldataAPI::saveLabelData:', error.message);
            return {};
        }
    }
}

class AutolabelAPI {
    constructor() {}

    // 调用自动标注接口（通过labeldata_id传递参数，图片从云端获取）
    // 传递的参数： labeldata_id
    async autolabelImage(labeldata_id) {
        try {
            const response = await axios.get(`${BASE_URL}/autolabel/${labeldata_id}?algo_id=ocr_v4`);
            // console.log('AutolabelAPI::autolabelImage resp = ', response.data);
            return response.data;
        } catch (error) {
            console.error('Error AutolabelAPI::autolabelImage:', error.message);
            return [];
        }
    }

    // 调用自动标注接口（通过image_base64传递参数，图片直接从本地发送）
    autolabelImageBase64(image_base64) {
        return new Promise((resolve, reject) => {
            axios
                .post(`${BASE_URL}/autolabel_base64`, {
                    image_base64: image_base64,
                    algo_id: 'ocr_rec_v4'
                })
                .then((response) => {
                    // console.log('AutolabelAPI::autolabelImageBase64 resp = ', response.data);
                    resolve(response.data.msg);
                })
                .catch((error) => {
                    // console.error('Error AutolabelAPI::autolabelImageBase64:', error.message);
                    reject([]);
                });
        });
    }
}

export { DatasetAPI, LabeldataAPI, AutolabelAPI };
